package com.halflife.comeElectricity.batteryCabinet;

import com.halflife.comeElectricity.battery.Battery;
import com.halflife.comeElectricity.battery.BatteryRepository;
import com.halflife.comeElectricity.batteryBox.BatteryBox;
import com.halflife.comeElectricity.batteryBox.BatteryBoxRepository;
import com.halflife.comeElectricity.member.rider.*;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import com.halflife.framework.exception.InValidException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/rider_bp")
public class BatteryCabinetController_Bp {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private RestTemplate template;
    @Resource
    private BatteryCabinetRepository batteryCabinetRepository;
    @Resource
    private BatteryBoxRepository batteryBoxRepository;
    @Resource
    private RiderOrderRepository riderOrderRepository;
    @Resource
    private BatteryRepository batteryRepository;
    @Resource
    private RiderRepository riderRepository;
    @Resource
    private OrderLogRepository orderLogRepository;

    private Map<String,Integer> operateMap = new HashMap<>();
    private Map<Integer,Integer> riderMap = new HashMap<>();

    @RequestMapping("/batteryCabinet/list")
    public List<BatteryCabinet> gotoList(@RequestParam(required = false) HashMap<String, Object> queryParam, Page page, HttpServletResponse response,
                                         HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        int totalCount = batteryCabinetRepository.selectCount(queryParam);
        List<BatteryCabinet> list = batteryCabinetRepository.selectListByPage(queryParam);
        return list;
    }

    @RequestMapping("/batteryBox/list")
    public List<BatteryBox> gotoBoxList(@RequestParam(required = false) HashMap<String, Object> queryParam, Page page, HttpServletResponse response,
                                        HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        List<BatteryBox> list = batteryBoxRepository.selectAll(queryParam);
        return list;
    }
    @RequestMapping("/order/list")
    public List<RiderOrder> gotoOrderList(@RequestParam(required = false) HashMap<String, Object> queryParam, Page page, HttpServletResponse response,
                                        HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        queryParam.put("endSql", "t.status>=0");
        List<RiderOrder> list = riderOrderRepository.selectAll(queryParam);
        return list;
    }
    @RequestMapping("/battery/operate")
    public ResponseEntity<Object> operateBattery(String code,Integer riderId, Page page, HttpServletResponse response,
                                              HttpServletRequest request, Model model) {

        Map map = new HashMap();
        Rider rider = riderRepository.selectByPrimaryKey(riderId);
        OrderLog log = new OrderLog();
        if (rider==null||rider.getState() < 1) {
            map.put("error", "您的会员还没有核准激活,请联系商家!");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (rider.getEndDate() == null) {
            map.put("error", "您还没有充值，充值后再来租借电池！");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (rider.getEndDate() <= new Date().getTime()) {
            map.put("error", "您的会员套餐已到期，请充值后再来租借电池");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        Map<String, Object> checkParam = new HashMap<>();
        checkParam.put("status", 0);
        checkParam.put("batteryNo", code);
        List<RiderOrder> checklist =  riderOrderRepository.selectAll(checkParam);
        if (checklist.size() > 0) {
            map.put("error", "当前电池正在被租借中，无法多次租借！");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("riderId", riderId);
        param.put("status", 0);
        List<RiderOrder> orderlist =  riderOrderRepository.selectAll(param);

        List<Battery> list =  batteryRepository.selectMany("select * from t_battery t where t.no='"+code+"'");
        if (list.size() > 0) {
            Battery battery = list.get(0);
            if (battery.getStatus() == 1) {
                map.put("error", "当前电池正在被租借中，无法多次租借！");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }else{
            map.put("error", "找不到此码对应的电池");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        if (orderlist.size() > 0) {
            //先归还电池
            RiderOrder order = orderlist.get(0);
            if (order.getBatteryNo().equals(code)) {
                map.put("error", "你正在租借此电池，无法多次租借!");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            RiderOrder update = new RiderOrder();
            update.setId(order.getId());
            update.setStatus(1);
            update.setEndDate(new Date().getTime());
            riderOrderRepository.updateByPrimaryKeySelective(update);
            //电池回盒子
            Battery battery = batteryRepository.selectByPrimaryKey(order.getBatteryId());
            battery.setStatus(0);
            battery.setOrderId(null);
            batteryRepository.updateByPrimaryKey(battery);
            log.setBackId(order.getId());
            log.setBackNo(battery.getNo());
            log.setCreateDate(new Date().getTime());
        }
        Battery battery = null;
        RiderOrder order = null;

        if (list.size() > 0) {
            battery = list.get(0);
            if (battery.getStatus() == 1) {
                map.put("error", "当前电池正在被租借中，无法多次租借！");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            order  = new RiderOrder();
            order.setRiderId(riderId);
            order.setRiderName(rider.getName());
            order.setPhone(rider.getPhone());
            order.setBatteryId(battery.getId());
            order.setBatteryNo(battery.getNo());
            order.setBeginDate(new Date().getTime());
            order.setCretaeDate(new Date().getTime());
            order.setStatus(0);
            order.setMoney(new BigDecimal(1));
            //
            Rider updateRider = new Rider();
            updateRider.setId(riderId);
            updateRider.setBalance(rider.getBalance().subtract(new BigDecimal(1)));
            riderRepository.updateByPrimaryKeySelective(updateRider);
            //
            riderOrderRepository.insert(order);
            //
            Battery updateBattery = new Battery();
            updateBattery.setId(battery.getId());
            updateBattery.setStatus(1);
            updateBattery.setOrderId(order.getId());
            batteryRepository.updateByPrimaryKeySelective(updateBattery);
            log.setTakeId(order.getId());
            log.setTakeNo(battery.getNo());
            log.setRiderName(rider.getName());
            log.setPhone(rider.getPhone());
            log.setRiderId(riderId);
            log.setStatus(0);
            orderLogRepository.insert(log);
        }

        return new ResponseEntity<Object>(order, HttpStatus.OK);
    }

    private class BatteryChecker{
        private Integer orderId;
        private String lockerId;
        private String boxId;
        private String batteryId;
        private BatteryCabinet batteryCabinet;
        private RiderOrder order;

        public BatteryChecker(Integer orderId, String lockerId, String boxId, String batteryId) {
            this.orderId = orderId;
            this.lockerId = lockerId;
            this.boxId = boxId;
            this.batteryId = batteryId;
        }
        public BatteryBox checkAndGetBatteryBox(Map returnMap) {
            BatteryBox batteryBox = batteryBoxRepository.selectOne("select * from  t_batterybox t where t.no='" + this.boxId + "'"+" and t.batteryCabinetId="+this.batteryCabinet.getId());
            if (batteryBox == null) {
                batteryBox = new BatteryBox();
                batteryBox.setNo(this.boxId);
                //throw new InValidException("找不到电池盒子"+boxId);
            }
            return batteryBox;
        }
        public Battery checkAndGetBattery(Map returnMap) {
            Battery battery = batteryRepository.selectOne("select * from  t_battery t where t.no='" + this.batteryId + "'");
            if (battery == null) {
                battery = new Battery();
                battery.setNo(this.batteryId);
                //throw new InValidException("找不到电池"+batteryId);
            }
            return battery;
        }
        public BatteryCabinet checkAndGetBatteryCabinet(Map returnMap) {
            batteryCabinet = batteryCabinetRepository.selectOne("select * from  t_batterycabinet t where t.no='" + lockerId + "'");
            if (batteryCabinet == null) {
                throw new InValidException("找不到柜子"+lockerId);
            }
            return batteryCabinet;
        }
        public RiderOrder checkAndGetOrder(Map returnMap) {
            order = riderOrderRepository.selectByPrimaryKey(orderId);
            if (order == null) {
                throw new InValidException("找不到订单"+orderId);
            }
            return order;
        }

    }

    @RequestMapping("/mock/neworder")
    public ResponseEntity<Object> newOrder(Integer orderId,String lockerId,String boxId,String batteryId,Integer state,String message, HttpServletResponse response,
                                               HttpServletRequest request, Model model) {
        Map returnMap = new HashMap();
        log.debug("==========================return/notif");
        log.debug(orderId+"="+lockerId+"-"+boxId+"-"+batteryId+"-"+state);
        log.debug("==========================return/notif");
        RiderOrder order = null;
        if (this.operateMap.containsKey(lockerId) ){
            this.operateMap.remove(lockerId);
        }
        try {
            Map<String, Object> endSql = new HashMap<>();
            endSql.put("endSql", "t.name is not null");
            List<Rider> riders = riderRepository.selectAll(endSql);
            List<Battery> batteryList = new ArrayList<>();
            for (int k = 278; k < 392; k++) {
                Battery battery = batteryRepository.selectByPrimaryKey(k);
                if (battery != null) {
                    batteryList.add(battery);
                }
            }

            for (int i = 0; i < 120; i++) {
                Calendar c = Calendar.getInstance();
                c.add(Calendar.DAY_OF_YEAR,0-i);
                c.add(Calendar.HOUR, 0 - 14);
                for (Rider rider : riders) {
                    RiderOrder riderOrder = new RiderOrder();
                    Random random=new Random();
                    Battery battery = batteryList.get(random.nextInt(batteryList.size()));
                    riderOrder.setBatteryId(battery.getId());
                    riderOrder.setBatteryNo(battery.getNo());
                    riderOrder.setBackBatteryId(battery.getId());
                    riderOrder.setBackBatteryNo(battery.getNo());
                    riderOrder.setApiState(0);
                    riderOrder.setStatus(1);
                    riderOrder.setRiderId(rider.getId());
                    riderOrder.setRiderName(rider.getName());
                    riderOrder.setPhone(rider.getPhone());
                    riderOrder.setBeginDate(c.getTimeInMillis()+random.nextInt(5)*1000*60*60+random.nextInt(5)*1000*60+random.nextInt(5)*1000);
                    riderOrder.setCretaeDate(riderOrder.getBeginDate());
                    riderOrder.setBatteryCabinetName("沃尔玛电池柜");
                    riderOrder.setEndDate(c.getTimeInMillis()+1000*60*60*5+random.nextInt(5)*1000*60*60+random.nextInt(5)*1000*60+random.nextInt(5)*1000);
                    riderOrderRepository.insert(riderOrder);

                    RiderOrder riderOrder1 = new RiderOrder();
                    riderOrder1.setBatteryId(battery.getId());
                    riderOrder1.setBatteryNo(battery.getNo());
                    riderOrder1.setBackBatteryId(battery.getId());
                    riderOrder1.setBackBatteryNo(battery.getNo());
                    riderOrder1.setApiState(0);
                    riderOrder1.setStatus(1);
                    riderOrder1.setRiderId(rider.getId());
                    riderOrder1.setRiderName(rider.getName());
                    riderOrder1.setPhone(rider.getPhone());
                    riderOrder1.setBeginDate(riderOrder.getEndDate()+6000);
                    riderOrder1.setCretaeDate(riderOrder1.getBeginDate());
                    riderOrder1.setBatteryCabinetName("沃尔玛电池柜");
                    riderOrder1.setEndDate(c.getTimeInMillis()+1000*60*60*5+1000*60*60*5+random.nextInt(5)*1000*60*60+random.nextInt(5)*1000*60+random.nextInt(5)*1000);
                    riderOrderRepository.insert(riderOrder1);


                }

            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString(),e);
            returnMap.put("success", false);
            returnMap.put("message", "系统异常!"+e.getMessage());
            this.notifyWithError(order,"系统异常!"+e.getMessage());
            return new ResponseEntity<Object>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        returnMap.put("success", true);
        returnMap.put("message", "成功");
        return new ResponseEntity<Object>(returnMap, HttpStatus.OK);
    }

    @RequestMapping("/return/notify")
    public ResponseEntity<Object> returnNotify(Integer orderId,String lockerId,String boxId,String batteryId,Integer state,String message, HttpServletResponse response,
                                                        HttpServletRequest request, Model model) {
        Map returnMap = new HashMap();
        log.debug("==========================return/notif");
        log.debug(orderId+"="+lockerId+"-"+boxId+"-"+batteryId+"-"+state);
        log.debug("==========================return/notif");
        RiderOrder order = null;
        if (this.operateMap.containsKey(lockerId) ){
            this.operateMap.remove(lockerId);
        }
        try {
            BatteryChecker checker = new BatteryChecker(orderId, lockerId, boxId, batteryId);
            order = checker.checkAndGetOrder(returnMap);
            if (state == 1) {
                this.notifyWithError(order,message);
                returnMap.put("success", false);
                returnMap.put("message", message);
                return new ResponseEntity<Object>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            BatteryCabinet batteryCabinet = checker.checkAndGetBatteryCabinet(returnMap);
            BatteryBox batteryBox =checker.checkAndGetBatteryBox(returnMap);
            Battery battery = checker.checkAndGetBattery(returnMap);

            OrderLog log = new OrderLog();
            log.setBatteryId(battery.getId());
            log.setBatteryBoxId(batteryBox.getId());
            log.setBatteryCabinetId(batteryCabinet.getId());
            log.setBatteryNo(battery.getNo());
            log.setBatteryBoxNo(batteryBox.getNo());
            log.setBatteryCabinetNo(batteryCabinet.getNo());
            log.setOrderId(order.getId());
            log.setCreateDate(new Date().getTime());
            log.setRiderId(order.getRiderId());
            log.setRiderName(order.getRider().getName());
            log.setPhone(order.getRider().getPhone());
            log.setMemo("还电池成功");
            orderLogRepository.insert(log);

            RiderOrder update = new RiderOrder();
            update.setId(order.getId());
            update.setStatus(1);
            update.setEndDate(new Date().getTime());
            update.setBackBatteryId(battery.getId());
            update.setBackBatteryNo(battery.getNo());
            update.setBackBatteryBoxId(batteryBox.getId());
            update.setBackBatteryBoxNo(batteryBox.getNo());
            update.setBackBatteryCabinetNo(batteryCabinet.getNo());
            update.setApiState(2);
            riderOrderRepository.updateByPrimaryKeySelective(update);
            //电池回盒子
//            battery = batteryRepository.selectByPrimaryKey(order.getBatteryId());
//            battery.setStatus(0);
//            battery.setOrderId(null);
//            batteryRepository.updateByPrimaryKey(battery);
        } catch (InValidException ex) {
            this.notifyWithError(order, "接口异常,"+ex.getMessage());
            returnMap.put("success", false);
            returnMap.put("message", ex.getMessage());
            return new ResponseEntity<Object>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString(),e);
            returnMap.put("success", false);
            returnMap.put("message", "系统异常!"+e.getMessage());
            this.notifyWithError(order,"系统异常!"+e.getMessage());
            return new ResponseEntity<Object>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        returnMap.put("success", true);
        returnMap.put("message", "还电池成功");
        return new ResponseEntity<Object>(returnMap, HttpStatus.OK);
    }


    @RequestMapping("/borrow/notify")
    public ResponseEntity<Object> borrowNotify(Integer orderId,String lockerId,String boxId,String batteryId,Integer state,String message,String zdy, HttpServletResponse response,
                                                        HttpServletRequest request, Model model) {
        log.debug("==========================borrow/notif");
        log.debug(orderId+"="+lockerId+"-"+boxId+"-"+batteryId+"-"+state);
        log.debug("==========================borrow/notif");
        Map returnMap = new HashMap();
        RiderOrder order = null;
        if (this.operateMap.containsKey(lockerId) ){
            this.operateMap.remove(lockerId);
        }
        try {
            BatteryChecker checker = new BatteryChecker(orderId, lockerId, boxId, batteryId);
            order = checker.checkAndGetOrder(returnMap);
            if (state == 1) {
                this.notifyWithError(order, message);
                returnMap.put("success", false);
                returnMap.put("message", message);
                return new ResponseEntity<Object>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
            }else if (state == 1) {
                this.notifyWithError(order, message);
                returnMap.put("success", false);
                returnMap.put("message", message);
                return new ResponseEntity<Object>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            BatteryCabinet batteryCabinet = checker.checkAndGetBatteryCabinet(returnMap);
            BatteryBox batteryBox =checker.checkAndGetBatteryBox(returnMap);
            Battery battery = checker.checkAndGetBattery(returnMap);

            OrderLog log = new OrderLog();
            log.setBatteryId(battery.getId());
            log.setBatteryBoxId(batteryBox.getId());
            log.setBatteryCabinetId(batteryCabinet.getId());
            log.setBatteryNo(battery.getNo());
            log.setBatteryBoxNo(batteryBox.getNo());
            log.setBatteryCabinetNo(batteryCabinet.getNo());
            log.setOrderId(order.getId());
            log.setCreateDate(new Date().getTime());
            log.setRiderId(order.getRiderId());
            log.setRiderName(order.getRider().getName());
            log.setPhone(order.getRider().getPhone());
            log.setMemo("借电池成功");
            orderLogRepository.insert(log);

            RiderOrder update = new RiderOrder();
            update.setId(order.getId());
            update.setStatus(0);
            update.setBeginDate(new Date().getTime());
            update.setBatteryId(battery.getId());
            update.setBatteryNo(battery.getNo());
            update.setBatteryBoxId(batteryBox.getId());
            update.setBatteryBoxNo(batteryBox.getNo());
            update.setBatteryCabinetNo(batteryCabinet.getNo());
            update.setBatteryCabinetName(batteryCabinet.getName());
            update.setApiState(2);
            riderOrderRepository.updateByPrimaryKeySelective(update);
            //电池回盒子
//            Battery updateBattery = new Battery();
//            updateBattery.setId(battery.getId());
//            updateBattery.setStatus(2);
//            updateBattery.setOrderId(order.getId());
//            batteryRepository.updateByPrimaryKeySelective(battery);
        } catch (InValidException ex) {
            ex.printStackTrace();
            log.error(ex.toString(), ex);
            this.notifyWithError(order, "接口异常,"+ex.getMessage());
            returnMap.put("success", false);
            returnMap.put("message", ex.getMessage());
            return new ResponseEntity<Object>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString(), e);
            returnMap.put("success", false);
            returnMap.put("message", "系统异常!" + e.getMessage());
            this.notifyWithError(order, "系统异常!" + e.getMessage());
            return new ResponseEntity<Object>(returnMap, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        returnMap.put("success", true);
        returnMap.put("message", "借电池成功");
        return new ResponseEntity<Object>(returnMap, HttpStatus.OK);
    }
    @RequestMapping("/order/result")
    public ResponseEntity<Object> returnResult(Integer orderId, HttpServletResponse response,
                                                        HttpServletRequest request, Model model) {
        RiderOrder order = riderOrderRepository.selectByPrimaryKey(orderId);
        //apiState=1 有异常
        if (order.getApiState()!=null&&order.getApiState() == 1) {
            log.error("==================接口异常");
            log.error("==================orderId:"+order.getId()+":"+order.getApiMemo());
            log.error("==================接口异常");
//            RiderOrder update = new RiderOrder();
//            update.setId(order.getId());
//            update.setApiState(2);
//            riderOrderRepository.updateByPrimaryKeySelective(update);
        }
        return new ResponseEntity<Object>(order, HttpStatus.OK);
    }
    private void notifyWithError(RiderOrder order,String message){
        if (order != null) {
            RiderOrder update = new RiderOrder();
            update.setId(order.getId());
            update.setApiState(1);
            update.setApiMemo(message);
            riderOrderRepository.updateByPrimaryKeySelective(update);
        }

    }
    @RequestMapping("/borrow/result")
    public ResponseEntity<Object> borrowResult(Integer orderId, HttpServletResponse response,
                                                        HttpServletRequest request, Model model) {
        return new ResponseEntity<Object>("scucess", HttpStatus.OK);
    }
    @RequestMapping("/reset")
    public ResponseEntity<Object> operateBatteryCabinet(String code,HttpServletResponse response,
                                                        HttpServletRequest request, Model model) {
        if (operateMap!=null&&operateMap.containsKey(code)) {
            operateMap.remove(code);
        }else{
            return new ResponseEntity<Object>("柜子号【"+code+"】，没有被锁定！", HttpStatus.OK);
        }
        return new ResponseEntity<Object>(Boolean.TRUE, HttpStatus.OK);
    }
    @RequestMapping("/battery/newoperate")
    public ResponseEntity<Object> operateBatteryCabinet(String code,Integer riderId, Page page, HttpServletResponse response,
                                              HttpServletRequest request, Model model) {
        Map map = new HashMap();
        if (operateMap.containsKey(code)) {
            if(operateMap.get(code).intValue()==riderId){
                Map<String, Object> param = new HashMap<>();
                param.put("apiState", -1);
                param.put("riderId", riderId);
                List<RiderOrder> checkOrderList =  riderOrderRepository.selectAll(param);
                if (checkOrderList.size() > 0) {
                    RiderOrder error = checkOrderList.get(0);
                    //借电池中
                    if (error.getStatus() == -1) {
                        map.put("error", "借电池操作还未完成，请等待一分钟再来扫码");
                    }else
                    if (error.getStatus() == 0) {
                        map.put("error", "还电池操作还未完成，请等待一分钟再来扫码");
                    }
                    return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
                }
                map.put("error", "您有未结束操作，请等待一分钟再来扫码");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            map.put("error", "当前柜子忙!请等待一分钟再来扫码");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        RiderOrder order = null;
        try {
            BatteryCabinet batteryCabinet = batteryCabinetRepository.selectOne("select * from  t_batterycabinet t where t.no='" + code + "'");
            if (batteryCabinet == null) {
                map.put("error", "扫的码找不到对应的电柜，请确认扫码正确!");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            Rider rider = riderRepository.selectByPrimaryKey(riderId);
            if (!rider.getDepartmentId().equals(batteryCabinet.getDepartmentId())) {
                map.put("error", "您不是本Department的会员无法借电池，Department："+rider.getDepartment().getName());
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            OrderLog orderLog = new OrderLog();
            if (rider==null||rider.getState() < 1) {
                map.put("error", "您的会员还没有核准激活,请联系商家!");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            Map<String, Object> param = new HashMap<>();
            param.put("apiState", -1);
            param.put("riderId", riderId);
            List<RiderOrder> checkOrderList =  riderOrderRepository.selectAll(param);
            if (checkOrderList.size() > 0) {
                RiderOrder error = checkOrderList.get(0);
                //借电池中
                if (error.getStatus() == -1) {
                    map.put("error", "借电池操作还未完成，请等待一分钟再来扫码");
                }else
                if (error.getStatus() == 0) {
                    map.put("error", "还电池操作还未完成，请等待一分钟再来扫码");
                }
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            param.remove("apiState");
            param.put("status", 0);
            List<RiderOrder> orderlist =  riderOrderRepository.selectAll(param);
            operateMap.put(code, riderId);
            //有订单
            if (orderlist.size() > 0) {
                //先归还电池
                order = orderlist.get(0);
                //当前订单正在等待换电池，告知
//                if (order.getApiState()!=null&&order.getApiState() == 1) {
//                    log.debug("==========================battery/newoperate/operating");
//                    log.debug(order.getId().toString());
//                    log.debug("==========================battery/newoperate");
//                    return new ResponseEntity<Object>(order, HttpStatus.OK);
//                }
                //上次还电池没有成功
//                if (order.getApiState() == 1) {
//
//                }
                RiderOrder update = new RiderOrder();
                update.setId(order.getId());
                update.setBackBatteryCabinetNo(code);
                update.setApiState(-1);
                riderOrderRepository.updateByPrimaryKeySelective(update);
                String result = template.getForObject("http://47.105.65.229:9898/return?lockerId="+code+"&orderId="+order.getId(), String.class);
                log.debug("==========================battery/newoperate/return");
                log.debug(result);
                log.debug("==========================battery/newoperate");
            }else{
//                if (operating) {
//                    map.put("error", "您还没有充值，充值后再来租借电池！");
//                    return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
//                }

                if (rider.getEndDate() == null) {
                    map.put("error", "您还没有充值，充值后再来租借电池！");
                    return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
                }
                if (rider.getEndDate() <= new Date().getTime()) {
                    map.put("error", "您的会员套餐已到期，请充值后再来租借电池");
                    return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
                }
                order  = new RiderOrder();
                order.setBatteryCabinetNo(code);
                order.setBatteryCabinetName(batteryCabinet.getName());
                order.setRiderId(riderId);
                order.setRiderName(rider.getName());
                order.setPhone(rider.getPhone());
                order.setCretaeDate(new Date().getTime());
                order.setStatus(-1);
                order.setApiState(-1);
                order.setMoney(new BigDecimal(1));
                riderOrderRepository.insert(order);
                String result = template.getForObject("http://47.105.65.229:9898/borrow?lockerId="+code+"&orderId="+order.getId(), String.class);
                log.debug("==========================battery/newoperate/borrow");
                log.debug(result);
                log.debug("==========================battery/newoperate");
            }
            //发出链接后再锁定

        } catch (RestClientException e) {
            operateMap.remove(code);
            //异常重置回去
            this.notifyWithError(order,"接口异常");
            e.printStackTrace();
            log.error(e.toString(),e);
            map.put("error", "电池柜接口异常!");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Object>(order, HttpStatus.OK);
    }

    @RequestMapping("/battery/take")
    public ResponseEntity<Object> takeBattery(String code,Integer riderId, Page page, HttpServletResponse response,
                                             HttpServletRequest request, Model model) {
        Map map = new HashMap();
        Map<String, Object> param = new HashMap<>();
        param.put("riderId", riderId);
        param.put("status", 0);
        int nocount =  riderOrderRepository.selectCount(param);
        if (nocount > 0) {
            map.put("error", "您有未还的电池，请归还后再来租借电池");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        Battery battery = null;
        RiderOrder order = null;
        List<Battery> list =  batteryRepository.selectMany("select * from t_battery t where t.no='"+code+"'");
        if (list.size() > 0) {
            battery = list.get(0);
            if (battery.getStatus() == 1) {
                map.put("error", "当前电池正在订单中，请还完电池后再租借此电池");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            Rider rider = riderRepository.selectByPrimaryKey(riderId);
            if (rider.getBalance()==null||rider.getBalance().intValue() < 1) {
                map.put("error", "您的余额不足，请充值后再来租借电池");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
             order  = new RiderOrder();
            order.setRiderId(riderId);
            order.setRiderName(rider.getName());
            order.setPhone(rider.getPhone());
            order.setBatteryId(battery.getId());
            order.setBatteryNo(battery.getNo());
            order.setBeginDate(new Date().getTime());
            order.setCretaeDate(new Date().getTime());
            order.setStatus(0);
            order.setMoney(new BigDecimal(1));
            //
            Rider updateRider = new Rider();
            updateRider.setId(riderId);
            updateRider.setBalance(rider.getBalance().subtract(new BigDecimal(1)));
            riderRepository.updateByPrimaryKeySelective(updateRider);
            //
            riderOrderRepository.insert(order);
            //
            Battery updateBattery = new Battery();
            updateBattery.setId(battery.getId());
            updateBattery.setStatus(1);
            updateBattery.setOrderId(order.getId());
            batteryRepository.updateByPrimaryKey(battery);
        }else{
            map.put("error", "找不到此码对应的电池");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new ResponseEntity<Object>(order, HttpStatus.OK);
    }
    @RequestMapping("/battery/back")
    public ResponseEntity<Object> backBattery(String code,Integer riderId, Page page, HttpServletResponse response,
                                             HttpServletRequest request, Model model) {
        Map map = new HashMap();
        Map<String, Object> param = new HashMap<>();
        param.put("riderId", riderId);
        param.put("status", 0);
        List<RiderOrder> list =  riderOrderRepository.selectAll(param);
        if (list.size() > 0) {
            //改订单
            RiderOrder order = list.get(0);
            if (!order.getBatteryNo().equals(code)) {
                map.put("error", "您扫码的电池和租借的电池不是同一块");
                return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
            }
            RiderOrder update = new RiderOrder();
            update.setId(order.getId());
            update.setStatus(1);
            update.setEndDate(new Date().getTime());
            riderOrderRepository.updateByPrimaryKeySelective(update);
            //电池回盒子
            Battery battery = batteryRepository.selectByPrimaryKey(order.getBatteryId());
            battery.setStatus(0);
            battery.setOrderId(null);
            batteryRepository.updateByPrimaryKey(battery);
        }else{
            map.put("error", "您当前没有订单，不需要归还电池");
            return new ResponseEntity<Object>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Object>(list.get(0), HttpStatus.OK);
    }
    @RequestMapping("/batterybox/take")
    public ResponseEntity<Map> takeBatteryByBox(Integer id,Integer riderId, Page page, HttpServletResponse response,
                                             HttpServletRequest request, Model model) {
        Map map = new HashMap();
        Map<String, Object> param = new HashMap<>();
        param.put("riderId", riderId);
        param.put("status", 0);
        int nocount =  riderOrderRepository.selectCount(param);
        if (nocount > 0) {
            map.put("error", "您有未还的电池，请归还后再来租借电池");
            return new ResponseEntity<Map>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        BatteryBox box = batteryBoxRepository.selectByPrimaryKey(id);
        if (box.getStatus() == 0 || box.getBatteryId() == null) {
            map.put("error", "当前电池盒子已经没有电池");
            return new ResponseEntity<Map>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        Rider rider = riderRepository.selectByPrimaryKey(riderId);
        Battery battery = batteryRepository.selectByPrimaryKey(box.getBatteryId());
        if (rider.getBalance()==null||rider.getBalance().intValue() < 1) {
            map.put("error", "您的余额不足，请充值后再来租借电池");
            return new ResponseEntity<Map>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        RiderOrder order  = new RiderOrder();
        order.setRiderId(riderId);
        order.setRiderName(rider.getName());
        order.setPhone(rider.getPhone());
        order.setBatteryBoxId(box.getId());
        order.setBatteryBoxNo(box.getNo());
        order.setBatteryCabinetName(box.getBatteryCabinet().getName());
        order.setBatteryCabinetNo(box.getBatteryCabinet().getNo());
        order.setBatteryId(box.getBatteryId());
        order.setBatteryNo(box.getBattery().getNo());
        order.setBeginDate(new Date().getTime());
        order.setCretaeDate(new Date().getTime());
        order.setStatus(0);
        order.setMoney(new BigDecimal(1));

        Rider updateRider = new Rider();
        updateRider.setId(riderId);
        updateRider.setBalance(rider.getBalance().subtract(new BigDecimal(1)));
        riderRepository.updateByPrimaryKeySelective(updateRider);
        riderOrderRepository.insert(order);
        //todo 盒子去掉电池 先去掉
        //盒子空了
        box.setBatteryId(null);
        box.setStatus(0);
        batteryBoxRepository.updateByPrimaryKey(box);
        //电池空了
        battery.setBatteryBoxId(null);
        batteryRepository.updateByPrimaryKey(battery);
        return new ResponseEntity<Map>(map, HttpStatus.OK);
    }
    @RequestMapping("/batterybox/back")
    public ResponseEntity<Map> backBatteryByBox(Integer id,Integer riderId, Page page, HttpServletResponse response,
                                             HttpServletRequest request, Model model) {
        Map map = new HashMap();
        Map<String, Object> param = new HashMap<>();
        param.put("riderId", riderId);
        param.put("status", 0);
        List<RiderOrder> list =  riderOrderRepository.selectAll(param);
        if (list.size() > 0) {
            //改订单
            RiderOrder order = list.get(0);
            RiderOrder update = new RiderOrder();
            update.setId(order.getId());
            update.setStatus(1);
            update.setEndDate(new Date().getTime());
            riderOrderRepository.updateByPrimaryKeySelective(update);
            //电池回盒子
            BatteryBox updateBox = new BatteryBox();
            updateBox.setId(id);
            updateBox.setBatteryId(order.getBatteryId());
            updateBox.setStatus(1);
            batteryBoxRepository.updateByPrimaryKeySelective(updateBox);
            //电池添加盒子
            Battery updateBattery = new Battery();
            updateBattery.setStatus(1);
            updateBattery.setBatteryBoxId(id);
            updateBattery.setId(order.getBatteryId());
            batteryRepository.updateByPrimaryKeySelective(updateBattery);
        }else{
            map.put("error", "您当前没有订单，不需要归还电池");
            return new ResponseEntity<Map>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Map>(map, HttpStatus.OK);
    }}
